package com.ruoyi.whzj.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import com.ruoyi.common.utils.BigDecimalUtil;
import com.ruoyi.common.utils.EmptyUtils;
import com.ruoyi.whzj.domain.*;
import com.ruoyi.whzj.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 用户Controller
 * 
 * @author ruoyi
 * @date 2020-10-15
 */
@Controller
@RequestMapping("/whzj/user")
public class WhUserController extends BaseController
{
    private String prefix = "whzj/user";

    @Autowired
    private IWhUserService whUserService;
    @Autowired
    private IWhBalancerecordService whBalancerecordService;
    @Autowired
    private IWhIntegralHistoryService whIntegralHistoryService;
    @Autowired
    private IWhExperiencerecordService whExperiencerecordService;
    @Autowired
    private IWhMemberlevelService whMemberlevelService;
    @Autowired
    private IWhzjBaseconfigService whzjBaseconfigService;
    @Autowired
    private IWhUserwithdrawService whUserwithdrawService;
    @RequiresPermissions("whzj:user:view")
    @GetMapping(value = "/user")
    public String user()
    {
        return prefix + "/user";
    }

    @RequiresPermissions("whzj:user:view")
    @GetMapping(value = "/proxyUser")
    public String proxyUser()
    {
        return prefix + "/proxyUser";
    }

    /**
     * 查询用户列表
     */
    @RequiresPermissions("whzj:user:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(WhUser whUser)
    {
        startPage();
        List<WhUser> list = whUserService.selectWhUserList(whUser);
        for(WhUser temp :list){
            WhUserwithdraw whUserwithdraw = new WhUserwithdraw();
            whUserwithdraw.setStatus("已转账");
            whUserwithdraw.setUserId(temp.getId());
            BigDecimal stringFir = new BigDecimal("0.0");
            for(WhUserwithdraw tempin:whUserwithdrawService.selectWhUserwithdrawList(whUserwithdraw)){
                stringFir = stringFir.add(tempin.getWithdrawMoney());
            }
            temp.setUserWithDraw(stringFir);
        }
        return getDataTable(list);
    }
    /**
     * 查询用户列表
     */
    @RequiresPermissions("whzj:user:list")
    @PostMapping("/listChild")
    @ResponseBody
    public TableDataInfo listChild(String mid)
    {
        startPage();
        /*WhBalancerecord whBalancerecord = new WhBalancerecord();
        whBalancerecord.setUserId(mid);
        List<WhBalancerecord> whBalancerecordList = whBalancerecordService.selectSharerecordList(whBalancerecord);*/
        //获取一级代理目录
        WhUser whUser = whUserService.selectWhUserById(mid);
        List<WhUser> whUserList = whUserService.selectWhUserByPCode(whUser.getInvitationCode());
        for(WhUser temp : whUserList){
            temp.setProxyLevel("一级代理用户");
        }
        //获取二级代理目录
        List<WhUser> whUserList1 = whUserService.selectWhUserByPPCode(whUser.getInvitationCode());
        for(WhUser temp : whUserList1){
            temp.setProxyLevel("二级代理用户");
        }
        List<WhUser> resultList = new ArrayList<>();
        resultList.addAll(whUserList);
        resultList.addAll(whUserList1);
        return getDataTable(resultList);
    }

    /**
     * 查询代理列表
     */
    @RequiresPermissions("whzj:user:list")
    @PostMapping("/listProxy")
    @ResponseBody
    public TableDataInfo listProxy(WhUser whUser)
    {
        startPage();
        whUser.setUserGroup("代理用户");
        List<WhUser> list = whUserService.selectWhUserList(whUser);
        for(WhUser temp :list){
            WhUserwithdraw whUserwithdraw = new WhUserwithdraw();
            whUserwithdraw.setStatus("已转账");
            whUserwithdraw.setUserId(temp.getId());
            BigDecimal stringFir = new BigDecimal("0.0");
            for(WhUserwithdraw tempin:whUserwithdrawService.selectWhUserwithdrawList(whUserwithdraw)){
                stringFir = stringFir.add(tempin.getWithdrawMoney());
            }
            temp.setUserWithDraw(stringFir);
        }
        return getDataTable(list);
    }

    /**
     * 启用
     */
    @RequiresPermissions("whzj:user:list")
    @PostMapping("/openUser")
    @ResponseBody
    public AjaxResult openUser(String id)
    {
        WhUser whUser = new WhUser();
        whUser.setId(id);
        whUser.setIsDisable("1");
        int num = whUserService.updateWhUser(whUser);
        return toAjax(num);
    }

    /**
     * 启用
     */
    @RequiresPermissions("whzj:user:list")
    @PostMapping("/openComplain")
    @ResponseBody
    public AjaxResult openComplain(String id)
    {
        WhUser whUser = new WhUser();
        whUser.setId(id);
        whUser.setIsComplaint("0");
        int num = whUserService.updateWhUser(whUser);
        return toAjax(num);
    }

    /**
     * 禁用
     */
    @RequiresPermissions("whzj:user:list")
    @PostMapping("/closeUser")
    @ResponseBody
    public AjaxResult closeUser(String id)
    {
        WhUser whUser = new WhUser();
        whUser.setId(id);
        whUser.setIsDisable("0");
        int num = whUserService.updateWhUser(whUser);
        return toAjax(num);
    }

    /**
     * 禁用
     */
    @RequiresPermissions("whzj:user:list")
    @PostMapping("/closeComplain")
    @ResponseBody
    public AjaxResult closeComplain(String id)
    {
        WhUser whUser = new WhUser();
        whUser.setId(id);
        whUser.setIsComplaint("1");
        int num = whUserService.updateWhUser(whUser);
        return toAjax(num);
    }

    /**
     * 导出用户列表
     */
    @RequiresPermissions("whzj:user:export")
    @Log(title = "用户", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(WhUser whUser)
    {
        List<WhUser> list = whUserService.selectWhUserList(whUser);
        ExcelUtil<WhUser> util = new ExcelUtil<WhUser>(WhUser.class);
        return util.exportExcel(list, "user");
    }

    /**
     * 新增用户
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }
    /**
     * 增减余额
     */
    @GetMapping("/balance/{id}")
    public String balance(@PathVariable("id") String id, ModelMap mmap)
    {
        WhUser whUser = whUserService.selectWhUserById(id);
        mmap.put("whUser", whUser);
        return prefix + "/balance";
    }

    /**
     * 增减余额
     */
    @RequiresPermissions("whzj:user:edit")
    @Log(title = "增减余额", businessType = BusinessType.UPDATE)
    @PostMapping("/balance")
    @ResponseBody
    public AjaxResult balance(String id, BigDecimal balance)
    {
        WhUser userP = whUserService.selectWhUserById(id);
        WhUser whUser = new WhUser();
        whUser.setId(id);
        whUser.setBalance(balance);
        int num = whUserService.updateWhUserBalance(whUser);
        if(num >0){
            //修改余额变动表
            WhBalancerecord whBalancerecord = new WhBalancerecord();
            whBalancerecord.setBalance(balance);
            whBalancerecord.setUserId(id);
            whBalancerecord.setOperate("4");
            whBalancerecord.setFront(userP.getBalance());
            whBalancerecord.setAfter(new BigDecimal(userP.getBalance().doubleValue() + balance.doubleValue()).setScale(2, BigDecimal.ROUND_HALF_UP));
            whBalancerecordService.insertWhBalancerecord(whBalancerecord);
        }
        return toAjax(num);
    }


    /**
     * 增减积分
     */
    @GetMapping("/integral/{id}")
    public String integral(@PathVariable("id") String id, ModelMap mmap)
    {
        WhUser whUser = whUserService.selectWhUserById(id);
        mmap.put("whUser", whUser);
        return prefix + "/integral";
    }

    /**
     * 增减积分
     */
    @RequiresPermissions("whzj:user:edit")
    @Log(title = "增减积分", businessType = BusinessType.UPDATE)
    @PostMapping("/integral")
    @ResponseBody
    public AjaxResult integral(String id, int integral)
    {
        WhUser whUser = new WhUser();
        whUser.setId(id);
        whUser.setIntegral(integral);
        int num = whUserService.updateWhUserIntegral(whUser);
        if(num >0){
            //修改积分变动表
            WhIntegralHistory whIntegralHistory = new WhIntegralHistory();
            whIntegralHistory.setIntegral(integral);
            whIntegralHistory.setUserId(id);
            whIntegralHistory.setOperat("8");
            whIntegralHistoryService.insertWhIntegralHistory(whIntegralHistory);
        }
        return toAjax(num);
    }

    /**
     * 增减经验
     */
    @GetMapping("/experience/{id}")
    public String experience(@PathVariable("id") String id, ModelMap mmap)
    {
        WhUser whUser = whUserService.selectWhUserById(id);
        mmap.put("whUser", whUser);
        return prefix + "/experience";
    }

    /**
     * 增减经验
     */
    @RequiresPermissions("whzj:user:edit")
    @Log(title = "增减积分", businessType = BusinessType.UPDATE)
    @PostMapping("/experience")
    @ResponseBody
    public AjaxResult experience(String id, int experience)
    {
        //根据Id获取用户信息
        WhUser whUser1 = whUserService.selectWhUserById(id);
        int oldExperience = whUser1.getExperience();
        WhUser whUser = new WhUser();
        whUser.setId(id);
        whUser.setExperience(experience);
        int num = whUserService.updateWhUserExperience(whUser);
        if(num >0){
            //修改经验变动表
            WhExperiencerecord whExperiencerecord = new WhExperiencerecord();
            whExperiencerecord.setExperience(experience);
            whExperiencerecord.setUserId(id);
            whExperiencerecord.setOperate("2");
            whExperiencerecordService.insertWhExperiencerecord(whExperiencerecord);
            //判断用户会员级别
            List<WhMemberlevel> memberlevelList = whMemberlevelService.selectWhMemberlevelList(new WhMemberlevel());
            WhUser whUser2 = new WhUser();
            whUser2.setId(id);
            for(int i=memberlevelList.size()-1;i>=0;i--){
                WhMemberlevel level = memberlevelList.get(i);
                 if((oldExperience+experience) >=level.getNeedExperience()){
                     whUser2.setLevel(level.getId());
                     break;
                 }
            }
            whUserService.updateWhUser(whUser2);
        }
        return toAjax(num);
    }

    /**
     * 修改用户组
     */
    @GetMapping("/userGroup/{id}")
    public String userGroup(@PathVariable("id") String id, ModelMap mmap)
    {
        WhUser whUser = whUserService.selectWhUserById(id);
        mmap.put("whUser", whUser);
        return prefix + "/userGroup";
    }

    /**
     * 修改用户组
     */
    @RequiresPermissions("whzj:user:edit")
    @Log(title = "修改用户组", businessType = BusinessType.UPDATE)
    @PostMapping("/userGroup")
    @ResponseBody
    public AjaxResult userGroup(WhUser whUser)
    {
        return toAjax(whUserService.updateWhUser(whUser));
    }

    /**
     * 新增保存用户
     */
    @RequiresPermissions("whzj:user:add")
    @Log(title = "用户", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(WhUser whUser)
    {
        return toAjax(whUserService.insertWhUser(whUser));
    }

    /**
     * 修改用户
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        WhUser whUser = whUserService.selectWhUserById(id);
        mmap.put("whUser", whUser);
        return prefix + "/edit";
    }

    /**
     * 修改保存用户
     */
    @RequiresPermissions("whzj:user:edit")
    @Log(title = "用户", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(WhUser whUser)
    {
        WhUser whUser1 = whUserService.selectWhUserById(whUser.getId());
        if(EmptyUtils.isNotEmpty(whUser.getUserGroup()) && "代理用户".equals(whUser.getUserGroup())){
            if(EmptyUtils.isEmpty(whUser1.getCommission()) && EmptyUtils.isEmpty(whUser1.getSecondDistirrate())){
                //赋值
                WhzjBaseconfig whzjBaseconfig = whzjBaseconfigService.selectWhzjBaseconfigById("1");
                whUser.setCommission(String.valueOf(whzjBaseconfig.getFirstDistrirate()));
                whUser.setSecondDistirrate(String.valueOf(whzjBaseconfig.getSecondDistirrate()));
            }
        }
        return toAjax(whUserService.updateWhUser(whUser));
    }
  /**
     * 修改比例
     */
    @RequiresPermissions("whzj:user:edit")
    @Log(title = "修改比例", businessType = BusinessType.UPDATE)
    @PostMapping("/modifyRate")
    @ResponseBody
    public AjaxResult modifyRate(String id,String rate,int type)
    {
        WhUser whUser = new WhUser();
        whUser.setId(id);
        if(type == 1){
            whUser.setCommission(rate);
        }else if(type == 2){
            whUser.setSecondDistirrate(rate);
        }
        return toAjax(whUserService.updateWhUser(whUser));
    }

    /**
     * 删除用户
     */
    @RequiresPermissions("whzj:user:remove")
    @Log(title = "用户", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(whUserService.deleteWhUserByIds(ids));
    }
}
